package com.example.musicplayer.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.musicplayer.R;
import com.example.musicplayer.adapter.MusicListAdapter;
import com.example.musicplayer.bean.Album;
import com.example.musicplayer.bean.Song;
import com.example.musicplayer.utils.Data;
import com.example.musicplayer.utils.GetAllActivity;

import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MusicActivity extends AppCompatActivity {

    private List<Song> list ;
    private ImageView img_music_pic;
    private TextView txtv_music_name;


    private Album album;

    private Boolean isWEBAlbum;

    private Button btn_music_upload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        GetAllActivity.getInstance().addActivity(this);
        isWEBAlbum = getIntent().getBooleanExtra("isWEBAlbum",false);
        //获取组件
        ImageView btn_music_back = findViewById(R.id.btn_music_back);
        ListView listView = (ListView) findViewById(R.id.list_music_main);
        img_music_pic = findViewById(R.id.img_music_pic);
        txtv_music_name = findViewById(R.id.txtv_music_name);
        btn_music_upload = findViewById(R.id.btn_music_upload);
        //上传监听事件
        if(isWEBAlbum){
            btn_music_upload.setVisibility(View.INVISIBLE);
        }
        btn_music_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Data data = (Data)getApplication();
                String url = getString(R.string.web_ip)+"/songs";
                System.out.println(url);
                for(Song song :list){
//                    System.out.println(song.song);
//                    System.out.println(song.singer);
//                    System.out.println(song.path);
//                    System.out.println(song.duration);
//                    System.out.println(song.size);
//                    System.out.println(song.albumId);

                    File music = new File(song.path);

//                    System.out.println(music.getName());
                    if(music.exists()){
                        String src = getString(R.string.web_ip)+"/upload/music";
                        OkHttpClient okHttpClient = new OkHttpClient();
                        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), music);
                        RequestBody requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("file", music.getName(), fileBody)
                                .build();
                        Request request = new Request.Builder()
                                .url(src)
                                .post(requestBody)
                                .build();
                        Call call = okHttpClient.newCall(request);
                        call.enqueue(new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {

                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                String data = response.body().string();
                                String src = getString(R.string.web_ip)+"/upload/msg";
                                MediaType JSON = MediaType.parse("application/json;charset=utf-8");
                                JSONObject json = new JSONObject();
                                try {
                                    json.put("song",music.getName());
                                    json.put("singer",song.singer);
                                    json.put("duration",song.duration);
                                    json.put("size",song.size);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                RequestBody body = RequestBody.create(JSON,json.toJSONString()); // new
                                final Request request = new Request.Builder()
                                        .url(src)
                                        .post(body)
                                        .build();
                                okHttpClient.newCall(request).enqueue(new Callback() {
                                    @Override
                                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                                    }

                                    @Override
                                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                        String data = response.body().string();
                                        System.out.println(data);
                                        String src = getString(R.string.web_ip)+"/upload/cover";
                                        Bitmap cover = getAlbumArt(song.albumId);
                                        File coverFile = getFile(cover,music.getName());
                                        OkHttpClient okHttpClient = new OkHttpClient();
                                        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"),coverFile);
                                        RequestBody requestBody = new MultipartBody.Builder()
                                                .setType(MultipartBody.FORM)
                                                .addFormDataPart("file", music.getName(), fileBody)
                                                .build();
                                        Request request = new Request.Builder()
                                                .url(src)
                                                .post(requestBody)
                                                .build();
                                        okHttpClient.newCall(request).enqueue(new Callback() {
                                            @Override
                                            public void onFailure(@NotNull Call call, @NotNull IOException e) {

                                            }

                                            @Override
                                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                                String data = response.body().string();
                                                System.out.println(data);
                                            }
                                        });
                                    }
                                });

                            }
                        });

                    }





                }
            }
        });
        //导航栏返回监听事件
        btn_music_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicActivity.this.finish();
            }
        });
        //音乐listView Adapter设置
//        list = MusicUtils.getMusicData(this);
        album = (Album) getIntent().getSerializableExtra("album");
        list = album.getSongList();
        txtv_music_name.setText(album.getName());
        //初始化封面图
        img_music_pic.setImageBitmap(album.getAlbumCover());

        MusicListAdapter adapter = new MusicListAdapter(this,list);
        listView.setAdapter(adapter);
        //音乐listView 点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(MusicActivity.this,PlayerActivity.class);
                intent.putExtra("path",list.get(position).path);
                intent.putExtra("musicData",(Serializable) list);
                intent.putExtra("position",position);
                intent.putExtra("isWEBAlbum",isWEBAlbum);
                startActivity(intent);
//                System.out.println("点击事件:");
//                System.out.println("path:"+list.get(position).path);
//                System.out.println("name:"+list.get(position).song);
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                PopupMenu popup = new PopupMenu(parent.getContext(), view);//第二个参数是绑定的那个view
                //获取菜单填充器
                MenuInflater inflater = popup.getMenuInflater();
                //填充菜单
                inflater.inflate(R.menu.menu_music, popup.getMenu());
                //绑定菜单项的点击事件
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.item_menu_music_collect:
                                HashMap<Integer,String> menuMap = new HashMap<>();
                                final Data data = (Data)getApplication();
                                String url = getString(R.string.web_ip)+"/list/all/"+data.getUserID();
                                OkHttpClient okHttpClient = new OkHttpClient();
                                final Request request = new Request.Builder()
                                        .url(url)
                                        .get()
                                        .build();
                                Call call = okHttpClient.newCall(request);
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                                    }

                                    @Override
                                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                        String json = response.body().string();
                                        List<HashMap> list = JSON.parseArray(json, HashMap.class);
                                        for(int i=0;i<list.size();i++){
                                            menuMap.put(Integer.parseInt(list.get(i).get("id").toString()),list.get(i).get("name").toString());
                                        }
                                        PopupMenu popupMenu = new PopupMenu(parent.getContext(), view);
                                        android.view.Menu menu_more = popupMenu.getMenu();
                                        int i=1;
                                        for(Map.Entry<Integer,String> h : menuMap.entrySet()){
                                            menu_more.add(android.view.Menu.NONE,h.getKey(),1,h.getValue());
                                        }
                                        popupMenu.getMenuInflater().inflate(R.menu.menu_music_collect, menu_more);
                                        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                                            @Override
                                            public boolean onMenuItemClick(MenuItem item) {
                                                String url = getString(R.string.web_ip)+"/list/add";
                                                OkHttpClient okHttpClient = new OkHttpClient();
                                                MediaType JSON = MediaType.parse("application/json;charset=utf-8");
                                                JSONObject json = new JSONObject();
                                                try {
                                                    json.put("list_id",item.getItemId());
                                                    json.put("song_id",album.getSongList().get(position).id);
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                                RequestBody body = RequestBody.create(JSON,json.toJSONString()); // new
                                                final Request request = new Request.Builder()
                                                        .url(url)
                                                        .post(body)
                                                        .build();
                                                Call call = okHttpClient.newCall(request);
                                                call.enqueue(new Callback() {
                                                    @Override
                                                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                                                    }

                                                    @Override
                                                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                                        Looper.prepare();
                                                        Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
                                                        Looper.loop();
                                                    }
                                                });
                                                return false;
                                            }
                                        });
                                        Looper.prepare();
                                        popupMenu.show();
                                        Looper.loop();
                                    }
                                });

                                break;
                            case R.id.item_menu_music_download:

                                break;
                            case R.id.item_menu_music_say:

                                break;
                            case R.id.item_menu_music_delete:

                                break;
                        }
                        return false;
                    }
                });
                popup.show();
                return true;
            }
        });

    }


    private Bitmap getAlbumArt(long album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = this.getContentResolver().query(Uri.parse(mUriAlbums + "/" + Long.toString(album_id)), projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        Bitmap bm = null;
        if (album_art != null) {
            bm = BitmapFactory.decodeFile(album_art);
        } else {
            bm = BitmapFactory.decodeResource(getResources(), R.drawable.musicpic);
        }
        return bm;
    }

    //在这里抽取了一个方法   可以封装到自己的工具类中...
    public File getFile(Bitmap bitmap,String name) {
        System.out.println(name);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        File file = new File(Environment.getExternalStorageDirectory() + "/"+name);
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            InputStream is = new ByteArrayInputStream(baos.toByteArray());
            int x = 0;
            byte[] b = new byte[1024 * 100];
            while ((x = is.read(b)) != -1) {
                fos.write(b, 0, x);
            }
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }
}